﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Configuration;
using System.IO;

namespace DataLayer.Utilities
{
    /// <summary>
    /// Clase con métodos utilitarios
    /// </summary>
    public static class Utilidades
    {
        /// <summary>
        /// Envia un correo    
        /// </summary>
        /// <param name="to">Correo destino. Si son varios, separados por ";"</param>
        /// <param name="from">Correo origen</param>
        /// <param name="subject">Subject del correo</param>
        /// <param name="attach">Archivo a attachar al mail</param>
        /// <param name="nameSend">Nombre de quien envia</param>
        /// <param name="message">Mensaje a enviar en el correo</param>
        /// <returns></returns>
        public static bool sendMail(string to, string from, string subject, string attach, string nameSend, string message)
        {
            try
            {
                MailMessage oMsg = new MailMessage();
                MailAddress AddressSend = new MailAddress(from, nameSend);

                oMsg.From = AddressSend;
                oMsg.From.DisplayName.ToString();

                string[] AddressSplit = to.Split(';');

                for (int i = 0; i < AddressSplit.Length; i++)
                {
                    MailAddress AddressDest = new MailAddress(AddressSplit[i].ToString());
                    oMsg.To.Add(AddressDest);
                }

                oMsg.Subject = subject;
                oMsg.Body = message;
                oMsg.IsBodyHtml = true;

                //SmtpClient MailSMTP = new SmtpClient(ConfigurationManager.AppSettings["SMTP"].ToString());
                //CredentialCache creds = new CredentialCache();
                //creds.Add(ConfigurationManager.AppSettings["SMTP"].ToString(), 25, "LOGIN", new NetworkCredential(ConfigurationManager.AppSettings["CREDENCIALES_CORREO"].ToString(), ConfigurationManager.AppSettings["CREDENCIALES_CLAVE"].ToString()));
                //MailSMTP.Credentials = creds;
                //MailSMTP.EnableSsl = true;

                SmtpClient Mail = new SmtpClient(ConfigurationManager.AppSettings["hostMail"].ToString(), Convert.ToInt32(ConfigurationManager.AppSettings["mailPort"].ToString()));
                Mail.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["userNameMail"].ToString(), ConfigurationManager.AppSettings["passwordMail"].ToString());
                Mail.Send(oMsg);
                oMsg = null;

                return true;
            }
            catch
            {
                return false;
            }

        }

        /// <summary>
        /// Serializa el objeto que recibe como parámetro
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string Serializar(object obj)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
            System.IO.MemoryStream stream = new System.IO.MemoryStream();

            try
            {
                serializer.Serialize(stream, obj);
                stream.Position = 0;
                doc.Load(stream);
                return doc.InnerXml;
            }
            catch
            {
                throw;
            }
            finally
            {
                stream.Close();
                stream.Dispose();
            }
        }

        /// <summary>
        /// Deserializa un xml y lo retorna como un objeto. Para que funcione correctamente, el objeto debe haber sido
        /// serializado con el método "Serializar"
        /// </summary>
        /// <param name="xmlOfAnObject">Xml del objeto a deserializar</param>
        /// <param name="tipo">Tipo al cual se debe convertir el xml</param>
        /// <returns></returns>
        public static object Deserializar(string xmlOfAnObject, Type tipo)
        {

            System.IO.StringReader read = new StringReader(xmlOfAnObject);
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(tipo);
            System.Xml.XmlReader reader = new System.Xml.XmlTextReader(read);

            try
            {
                return serializer.Deserialize(reader);
            }
            catch
            {
                throw;
            }
            finally
            {
                reader.Close();
                read.Close();
                read.Dispose();
            }
        }

    }
}
